const express = require("express");
const router = express.Router();
const Classify = require("../data/models/Classify");
const Document = require("../data/models/Document");
const Tag = require("../data/models/Tag");
const jwt = require("../controller/jwt");
const Search = require("../controller/Search");
module.exports = router;

/**
 * @api {get} /user/:id Request User information
 * @apiName GetUser
 * @apiGroup User
 *
 * @apiParam {Number} id Users unique ID.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 *
 * @apiSuccessExample Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *       "firstname": "felix",
 *       "lastname": "banfield"
 *     }
 *
 * @apiError UserNotFound The id of the User was not found.
 *
 * @apiErrorExample Error-Response:
 *     HTTP/1.1 404 Not Found
 *     {
 *       "error": "UserNotFound"
 *     }
 */

router.get("/ClassifyOne", (req, res) => {
  // 单个分类信息
  Classify.findOne({ _id: req.query._id }, (err, doc) => {
    if (err) res.status(500).send(err);
    res.send(doc);
  });
});

router
  .route("/")
  .get(jwt.check, (req, res) => {
    Search.Get(Classify, { title: { $regex: req.query.title } }, req, res, "tag");
    // { tag: { $elemMatch: { title: form.tag } } },
  })
  .post(jwt.check, async (req, res) => {
    if (req.body != undefined && JSON.stringify(req.body) != "{}") {
      let { title, name, tag } = req.body;
      Classify.findOne({ $or: [{ title }, { name }], user: req.user }, (err, doc) => {
        if (err) res.status(500).send(err);
        if (doc) {
          if (title == doc.title) res.send({ Code: 500, Msg: "已存在分类名称" });
          else if (name == doc.name) res.send({ Code: 500, Msg: "已存在分类英文名" });
        } else {
          let insertMany = new Classify({ ...req.body, user: req.user });
          insertMany.save(err => {
            if (err) return res.status(500).send(err);
            tag.forEach(v => (v.classify = insertMany._id));
            Tag.insertMany(tag);
            res.send({ Code: 200, Msg: "新增成功" });
          });
        }
      });
    } else res.send({ Code: 500, Msg: "新增失败" });
  })
  .put(jwt.check, async (req, res) => {
    if (req.body != undefined && JSON.stringify(req.body) != "{}") {
      // let { title, tag } = req.body;
      // let record = [...new Set(tag)]; // 去重  前端已去重
      let { _id, name, title, tag } = req.body;
      const classifyFind = await Classify.findById(_id);
      // console.log("classifyFind", classifyFind);
      classifyFind.name = name;
      classifyFind.title = title;
      await classifyFind.save();
      await Tag.deleteMany({ classify: _id });
      tag.forEach(v => (v.classify = _id));
      await Tag.insertMany(tag);
      res.send({ Code: 200, Msg: "修改成功" });
    } else res.send({ Code: 500, Msg: "修改失败" });
  })
  .delete(jwt.check, async (req, res) => {
    let id = req.query._id;
    await Classify.findByIdAndDelete(id);
    await Document.deleteMany({ classify: id });
    await Tag.deleteMany({ classify: id });
    res.send({ Code: 200, Msg: "删除成功" });
  });

router.get("/List", jwt.check, (req, res) => {
  Classify.find({ user: req.user })
    .populate("tag")
    .lean()
    .then(doc => {
      res.send(doc);
    });
});

router.get("/Doc", jwt.check, (req, res) => {
  Classify.findOne({ user: req.user, name: req.query.name })
    .populate("Documents")
    // .lean()
    .then(doc => {
      res.send({ List: doc.Documents });
    });
});
